package com.longcai.service.impl.customer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.constants.OrderConstants;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.entity.customer.ClyjUserProperty;
import com.longcai.entity.customer.ClyjUserTouch;
import com.longcai.entity.customer.customerVo.ClyjFuyouSmallcompanyRegistervo;
import com.longcai.entity.exchangemall.ClyjExchangeMall;
import com.longcai.entity.homegood.ClyjGoodsHomepage;
import com.longcai.entity.homegood.ClyjGoodsSpec;
import com.longcai.entity.nearby.ClyjNearbyShopsGoods;
import com.longcai.entity.nearby.ClyjNearbyShopsGoodsSpec;
import com.longcai.entity.order.ClyjGoodsOrderDetails;
import com.longcai.entity.scm.ClyjCoupon;
import com.longcai.entity.scm.ClyjScmGoodsSpecZdy;
import com.longcai.entity.scm.ClyjScmGoodsZdy;
import com.longcai.mapper.customer.ClyjUserMapper;
import com.longcai.mapper.customer.ClyjUserPropertyMapper;
import com.longcai.mapper.customer.ClyjUserTouchMapper;
import com.longcai.mapper.exchange.ClyjExchangeMallMapper;
import com.longcai.mapper.fuyou.ClyjFuyouSmallcompanyRegisterMapper;
import com.longcai.mapper.homegood.ClyjGoodsHomepageMapper;
import com.longcai.mapper.homegood.ClyjGoodsSpecMapper;
import com.longcai.mapper.nearby.ClyjNearbyShopsGoodsMapper;
import com.longcai.mapper.nearby.ClyjNearbyShopsGoodsSpecMapper;
import com.longcai.mapper.nearby.ClyjNearbyShopsMapper;
import com.longcai.mapper.scm.ClyjCouponMapper;
import com.longcai.mapper.scm.ClyjScmGoodsSpecZdyMapper;
import com.longcai.mapper.scm.ClyjScmGoodsZdyMapper;
import com.longcai.service.customer.ClyjUserPropertyService;
import com.longcai.service.customer.ClyjUserTouchService;
import com.longcai.vo.ClyjGoodsOrderDetailsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 邀请关系表 服务实现类
 * </p>
 *
 * @author M
 * @since 2019-03-26
 */
@Service
public class ClyjUserTouchServiceImpl extends ServiceImpl<ClyjUserTouchMapper, ClyjUserTouch> implements ClyjUserTouchService {

    public ReentrantLock registLock = new ReentrantLock();

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjUserTouchMapper clyjUserTouchMapper;
    @Autowired
    private ClyjUserMapper clyjUserMapper;
    @Autowired
    private ClyjGoodsHomepageMapper clyjGoodsHomepageMapper;
    @Autowired
    private ClyjGoodsSpecMapper clyjGoodsSpecMapper;
    @Autowired
    private ClyjExchangeMallMapper clyjExchangeMallMapper;
    @Autowired
    private ClyjUserPropertyMapper clyjUserPropertyMapper;
    @Autowired
    private ClyjCouponMapper clyjCouponMapper;
    @Autowired
    private ClyjUserPropertyService clyjUserPropertyService;
    @Autowired
    private ClyjNearbyShopsMapper clyjNearbyShopsMapper;
    @Autowired
    private ClyjFuyouSmallcompanyRegisterMapper clyjFuyouSmallcompanyRegisterMapper;
    @Autowired
    private ClyjScmGoodsZdyMapper clyjScmGoodsZdyMapper;
    @Autowired
    private ClyjScmGoodsSpecZdyMapper clyjScmGoodsSpecZdyMapper;
    @Autowired
    private ClyjNearbyShopsGoodsMapper clyjNearbyShopsGoodsMapper;
    @Autowired
    private ClyjNearbyShopsGoodsSpecMapper clyjNearbyShopsGoodsSpecMapper;
    @Autowired
    private ClyjNearbyShopsGoodsMapper getClyjNearbyShopsGoodsMapper;


    /**
     * 新增用户邀请
     *
     * @param userPId
     * @param userPLevel
     * @param clyjUser
     */
    @Override
    public void saveTouch(String userPId, Integer userPLevel, ClyjUser clyjUser, Integer relationLevel) {

        try {
            ClyjUserTouch clyjUserTouch = new ClyjUserTouch();
            clyjUserTouch.setId(UUID.randomUUID().toString().replace("-", ""));
            clyjUserTouch.setUserId(clyjUser.getUserId());
            clyjUserTouch.setUserLevel(clyjUser.getLevel());
            clyjUserTouch.setUserPId(userPId);
            clyjUserTouch.setUserPLevel(userPLevel);
            clyjUserTouch.setCreateTime(new Date());
            clyjUserTouch.setRelationLevel(relationLevel);
            clyjUserTouch.setStatus("1");
            Integer integer = this.clyjUserTouchMapper.insert(clyjUserTouch);
            logger.debug("插入成功+++++++++++++++", integer);
        } catch (Exception e) {
            logger.debug("插入失败+++++++++++++++");
            e.printStackTrace();

        }

    }

    /**
     * 我的分享-我的导师
     *
     * @param userId
     * @return
     */
    @Override
    public ApiResult getUserShare(String userId) {
        try {
            //查询登录用户所属第一级上级
            QueryWrapper<ClyjUserTouch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("relation_level", 0);
            queryWrapper.eq("status", "2");
            ClyjUserTouch clyjUserTouch = this.clyjUserTouchMapper.selectOne(queryWrapper);
            //判断是否有永久推荐人
            if (clyjUserTouch == null) {
                //查询登录用户所属第一级上级
                QueryWrapper<ClyjUserTouch> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("user_id", userId);
                queryWrapper2.eq("relation_level", 0);
                queryWrapper2.eq("status", "1");
                ClyjUserTouch clyjUserTouch1 = this.clyjUserTouchMapper.selectOne(queryWrapper2);
                if (clyjUserTouch1 == null) {
                    logger.debug("暂无上级");
                    return ApiResult.success("暂无上级");
                }
            }
            //查询一级上级信息
            QueryWrapper<ClyjUser> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id", clyjUserTouch.getUserPId());
            ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper1);
            logger.debug("查询成功");
            return ApiResult.success(clyjUser);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }

    }

    /**
     * 邀约会员数量
     *
     * @param userId
     * @return
     */
    @Override
    public ApiResult getcount(String userId) {
        try {
            QueryWrapper<ClyjUserTouch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_p_id", userId);
            Integer integer = this.clyjUserTouchMapper.selectCount(queryWrapper);
            logger.debug("查询成功");
            return ApiResult.success(integer);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 个人二维码
     *
     * @param userId
     * @return
     */
    @Override
    public ApiResult getInfo(String userId) {
        try {
            QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper);
            logger.debug("查询成功");
            return ApiResult.success(clyjUser);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 已邀请会员
     *
     * @param userId
     * @return
     */
    @Override
    public ApiResult getInviteUser(String userId) {
        try {
            //查询邀请关系表（查询已邀请的id）
            QueryWrapper<ClyjUserTouch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_p_id", userId);
            List<ClyjUserTouch> clyjUserTouchList = this.clyjUserTouchMapper.selectList(queryWrapper);
            if (clyjUserTouchList.size() == 0) {
                return ApiResult.success(null);
            }
            List list = new ArrayList();
            //遍历取出已邀请id
            for (ClyjUserTouch clyjUserTouch : clyjUserTouchList) {
                list.add(clyjUserTouch.getUserId());
            }
            //查询用户表
            QueryWrapper<ClyjUser> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("user_id", list);
            List<ClyjUser> clyjUserList = this.clyjUserMapper.selectList(queryWrapper1);
            logger.debug("查询成功");
            return ApiResult.success(clyjUserList);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 已邀请导购
     *
     * @param userId
     * @return
     */
    @Override
    public ApiResult getInviteUserInfo(String userId) {

        try {
            //查询邀请关系表（查询已邀请的id）
            QueryWrapper<ClyjUserTouch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_p_id", userId);
            queryWrapper.eq("user_level", 1);
            List<ClyjUserTouch> clyjUserTouchList = this.clyjUserTouchMapper.selectList(queryWrapper);
            if (clyjUserTouchList.size() == 0) {
                return ApiResult.success(null);
            }
            List list = new ArrayList();
            //遍历取出已邀请id
            for (ClyjUserTouch clyjUserTouch : clyjUserTouchList) {
                list.add(clyjUserTouch.getUserId());
            }
            //查询用户表
            QueryWrapper<ClyjUser> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("user_id", list);
            List<ClyjUser> clyjUserList = this.clyjUserMapper.selectList(queryWrapper1);
            logger.debug("查询成功");
            return ApiResult.success(clyjUserList);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 订单过滤
     *
     * @param clyjGoodsOrderDetailsVo
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> testOrder(ClyjGoodsOrderDetailsVo clyjGoodsOrderDetailsVo, ClyjUser clyjUser) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        registLock.lock();
        Map<String, Integer> map = new HashMap<String, Integer>();
        try {
            //获取订单信息
            List<ClyjGoodsOrderDetails> clyjGoodsOrderDetails = clyjGoodsOrderDetailsVo.getClyjGoodsOrderDetails();
            QueryWrapper<ClyjGoodsHomepage> queryWrapper = new QueryWrapper<>();
            QueryWrapper<ClyjUserProperty> queryWrapper3 = new QueryWrapper<>();
            for (ClyjGoodsOrderDetails clyjGoodsOrderDetails1 : clyjGoodsOrderDetails) {
                //商品价格
                BigDecimal a1 = clyjGoodsOrderDetails1.getGoodsPrice();
                if (a1 != null && !a1.equals("")) {
                    //商品价格和0，Zero比较
                    int a = a1.compareTo(BigDecimal.ZERO);
                    map.put("a", a);
                } else {
                    map.put("a", 0);
                }
                //商品零钱
                BigDecimal b1 = clyjGoodsOrderDetails1.getPayBalance();
                if (b1 != null && !b1.equals("")) {
                    //商品零钱价格和0，Zero比较
                    int b = b1.compareTo(BigDecimal.ZERO);
                    map.put("b", b);
                } else {
                    map.put("b", 0);
                }
                //支付积分
                BigDecimal c1 = clyjGoodsOrderDetails1.getPayIntegral();
                if (c1 != null && !c1.equals("")) {
                    //支付积分和0，Zero比较
                    int c = c1.compareTo(BigDecimal.ZERO);
                    map.put("c", c);
                } else {
                    map.put("c", 0);
                }
                //支付红包
                BigDecimal d1 = clyjGoodsOrderDetails1.getPayRedPacket();
                if (d1 != null && !d1.equals("")) {
                    //支付红包和0，Zero比较
                    int d = d1.compareTo(BigDecimal.ZERO);
                    map.put("d", d);
                } else {
                    map.put("d", 0);
                }
                //礼品券
                BigDecimal e1 = clyjGoodsOrderDetails1.getPayCoupon();
                if (e1 != null && !e1.equals("")) {
                    //礼品券和0，Zero比较
                    int e = e1.compareTo(BigDecimal.ZERO);
                    map.put("e", e);
                } else {
                    map.put("e", 0);
                }
                //实际支付金额
                BigDecimal f1 = clyjGoodsOrderDetails1.getPayAmount();
                //购买数量
                BigDecimal i = new BigDecimal(clyjGoodsOrderDetails1.getGoodsAmount());

                //查询用户资产
                queryWrapper3.eq("user_id", clyjUser.getUserId());
                ClyjUserProperty clyjUserProperty = clyjUserPropertyMapper.selectOne(queryWrapper3);
                //查询用户礼品券
                QueryWrapper<ClyjCoupon> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("user_phone", clyjUser.getPhone());
                ClyjCoupon clyjCoupon = clyjCouponMapper.selectOne(queryWrapper4);
                //下单用户可用余额
                BigDecimal account = clyjUserProperty.getAccount().subtract(clyjUserProperty.getFreezePayAccount());
                //下单用户可用零钱
                BigDecimal money = clyjUserProperty.getShoestringMoney().subtract(clyjUserProperty.getFreezePayShoestringMoney());
                //下单用户可用红包
                BigDecimal red = clyjUserProperty.getRedPacket().subtract(clyjUserProperty.getFreezePayRedPacket());
                //下单用户可用礼品券
                BigDecimal price_sum = clyjCoupon.getPriceSum();
                //下单用户可用积分
                BigDecimal integral = clyjUserProperty.getIntegral().subtract(clyjUserProperty.getFreezePayIntegral());
                //现金加零钱组合
                if (map.get("a") > 0 && map.get("b") > 0) {
                    //判断商品所需价格是否一致
                    queryWrapper.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                    queryWrapper.eq("present_price", clyjGoodsOrderDetails1.getGoodsPrice());
                    queryWrapper.eq("pocket_money", clyjGoodsOrderDetails1.getPayBalance());
                    ClyjGoodsHomepage clyjGoodsHomepage = clyjGoodsHomepageMapper.selectOne(queryWrapper);
                    if (clyjGoodsHomepage == null) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "商品信息有误");
                        return resultMap;
                    }
                    ClyjGoodsSpec clyjGoodsSpec = this.clyjGoodsSpecMapper.selectSpec(clyjGoodsOrderDetails1.getSpecId());
                    //判断库存
                    if (clyjGoodsSpec.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount()) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "库存不足");
                        resultMap.put("data", clyjGoodsOrderDetails1.getGoodsAmount());
                        return resultMap;
                    }
                    //判断总价
                    if (f1.compareTo(a1.multiply(i)) != 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "支付金额不匹配");
                        return resultMap;
                    }
                    //判断个人资产
                    if (money.compareTo(b1.multiply(i)) < 0 && account.compareTo(a1.multiply(i)) < 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "账户余额不足");
                        resultMap.put("data", money);
                        return resultMap;

                    } else {
                        //冻结余额
                        clyjUserPropertyService.changeFinance(clyjUser.getUserId(), a1.multiply(i), "1", "订单", "3", clyjGoodsOrderDetails1.getTradeNo(), "0", null);
                        //冻结零钱
                        clyjUserPropertyService.changeFinance(clyjUser.getUserId(), b1.multiply(i), "1", "订单", "0", clyjGoodsOrderDetails1.getTradeNo(), "0", null);
                    }
                    //扣库存
                    clyjGoodsSpecMapper.updatenum(clyjGoodsOrderDetails1.getSpecId(), clyjGoodsOrderDetails1.getGoodsAmount());

                }
                //纯现金组合
                if (map.get("a") > 0 && map.get("b") <= 0) {
                    //判断商品所需价格是否一致
                    queryWrapper.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                    queryWrapper.eq("present_price", clyjGoodsOrderDetails1.getGoodsPrice());
                    ClyjGoodsHomepage clyjGoodsHomepage = clyjGoodsHomepageMapper.selectOne(queryWrapper);
                    if (clyjGoodsHomepage == null) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "商品信息有误");
                        return resultMap;
                    }
                    ClyjGoodsSpec clyjGoodsSpec = this.clyjGoodsSpecMapper.selectSpec(clyjGoodsOrderDetails1.getSpecId());
                    //判断库存
                    if (clyjGoodsSpec.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount()) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "库存不足");
                        resultMap.put("data", clyjGoodsOrderDetails1.getGoodsAmount());
                        return resultMap;
                    }
                    //判断总价
                    if (f1.compareTo(a1.multiply(i)) != 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "支付金额不匹配");
                        return resultMap;
                    }
                    //判断个人资产
                    if (account.compareTo(a1.multiply(i)) < 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "账户余额不足");
                        resultMap.put("data", money);
                        return resultMap;
                    } else {
                        //冻结余额
                        clyjUserPropertyService.changeFinance(clyjUser.getUserId(), a1.multiply(i), "1", "订单", "3", clyjGoodsOrderDetails1.getTradeNo(), "0", null);
                    }
                    //扣库存
                    clyjGoodsSpecMapper.updatenum(clyjGoodsOrderDetails1.getSpecId(), clyjGoodsOrderDetails1.getGoodsAmount());
                }
                //积分加现金
                if (map.get("a") > 0 && map.get("c") > 0) {
                    QueryWrapper<ClyjExchangeMall> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                    queryWrapper1.eq("price", clyjGoodsOrderDetails1.getGoodsPrice());
                    queryWrapper1.eq("integral", clyjGoodsOrderDetails1.getPayIntegral());
                    ClyjExchangeMall clyjExchangeMall = this.clyjExchangeMallMapper.selectOne(queryWrapper1);
                    if (clyjExchangeMall == null) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "商品信息有误");
                        return resultMap;
                    }
                    ClyjGoodsSpec clyjGoodsSpec = this.clyjGoodsSpecMapper.selectSpec(clyjGoodsOrderDetails1.getSpecId());
                    //判断库存
                    if (clyjGoodsSpec.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount()) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "库存不足");
                        resultMap.put("data", clyjGoodsOrderDetails1.getGoodsAmount());
                        return resultMap;
                    }
                    //判断总价
                    if (f1.compareTo(a1.multiply(i)) != 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "支付金额不匹配");
                        return resultMap;
                    }

                    //判断个人资产
                    if (integral.compareTo(c1.multiply(i)) < 0 && account.compareTo(a1.multiply(i)) < 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "账户余额不足");
                        resultMap.put("data", money);
                        return resultMap;
                    } else {
                        //冻结余额
                        clyjUserPropertyService.changeFinance(clyjUser.getUserId(), a1.multiply(i), "1", "订单", "3", clyjGoodsOrderDetails1.getTradeNo(), "0", null);
                        //冻结积分
                        clyjUserPropertyService.changeFinance(clyjUser.getUserId(), c1.multiply(i), "1", "订单", "2", clyjGoodsOrderDetails1.getTradeNo(), "0", null);
                    }
                    //扣库存
                    clyjGoodsSpecMapper.updatenum(clyjGoodsOrderDetails1.getSpecId(), clyjGoodsOrderDetails1.getGoodsAmount());
                }
                //红包
                if (map.get("a") <= 0 && map.get("b") <= 0 && map.get("c") <= 0 && map.get("e") <= 0 && map.get("d") > 0) {
                    QueryWrapper<ClyjExchangeMall> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                    queryWrapper1.eq("red_packet", clyjGoodsOrderDetails1.getPayRedPacket());
                    ClyjExchangeMall clyjExchangeMall = this.clyjExchangeMallMapper.selectOne(queryWrapper1);
                    if (clyjExchangeMall == null) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "商品信息有误");
                        return resultMap;
                    }
                    ClyjGoodsSpec clyjGoodsSpec = this.clyjGoodsSpecMapper.selectSpec(clyjGoodsOrderDetails1.getSpecId());
                    //判断库存
                    if (clyjGoodsSpec.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount()) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "库存不足");
                        resultMap.put("data", clyjGoodsOrderDetails1.getGoodsAmount());
                        return resultMap;
                    }
                    //判断总价
                    if (f1.compareTo(d1.multiply(i)) != 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "支付金额不匹配");
                        return resultMap;
                    }
                    //判断个人资产
                    if (red.compareTo(d1.multiply(i)) < 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "可用红包不足");
                        resultMap.put("data", money);
                        return resultMap;
                    } else {
                        //冻结红包
                        clyjUserPropertyService.changeFinance(clyjUser.getUserId(), d1.multiply(i), "1", "订单", "1", clyjGoodsOrderDetails1.getTradeNo(), "0", null);
                    }
                    //扣库存
                    clyjGoodsSpecMapper.updatenum(clyjGoodsOrderDetails1.getSpecId(), clyjGoodsOrderDetails1.getGoodsAmount());
                }
                //礼品券
                if (map.get("a") <= 0 && map.get("b") <= 0 && map.get("c") <= 0 && map.get("d") <= 0 && map.get("e") > 0) {
                    QueryWrapper<ClyjExchangeMall> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                    queryWrapper1.eq("gift_certificate", clyjGoodsOrderDetails1.getPayCoupon());
                    ClyjExchangeMall clyjExchangeMall = this.clyjExchangeMallMapper.selectOne(queryWrapper1);
                    if (clyjExchangeMall == null) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "商品信息有误");
                        return resultMap;
                    }
                    ClyjGoodsSpec clyjGoodsSpec = this.clyjGoodsSpecMapper.selectSpec(clyjGoodsOrderDetails1.getSpecId());
                    //判断库存
                    if (clyjGoodsSpec.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount()) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "库存不足");
                        resultMap.put("data", clyjGoodsOrderDetails1.getGoodsAmount());
                        return resultMap;
                    }
                    //判断总价
                    if (f1.compareTo(price_sum) != 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "可用礼品券不足");
                        return resultMap;
                    } else {
                        clyjGoodsSpecMapper.updatenum(clyjGoodsOrderDetails1.getSpecId(), clyjGoodsOrderDetails1.getGoodsAmount());
                    }
                    //判断个人资产
                    if (price_sum.compareTo(e1.multiply(i)) < 0) {
                        resultMap.put("code", "fail");
                        resultMap.put("errorMsg", "可用礼品券不足");
                        resultMap.put("data", money);
                        return resultMap;
                    } /*else {
                        //冻结余额
                        clyjUserPropertyService.changeFinance(clyjUser.getUserId(), b1.multiply(i), "1", "订单", "3", clyjGoodsOrderDetails1.getTradeNo(), "0", null);
                        //冻结零钱
                        clyjUserPropertyService.changeFinance(clyjUser.getUserId(), b1.multiply(i), "1", "订单", "0", clyjGoodsOrderDetails1.getTradeNo(), "0", null);
                    }*/
                    //扣库存
                    clyjGoodsSpecMapper.updatenum(clyjGoodsOrderDetails1.getSpecId(), clyjGoodsOrderDetails1.getGoodsAmount());
                }
                List<ClyjFuyouSmallcompanyRegistervo> clyjTouchVo = getTouch(clyjUser.getUserId(), clyjUser.getLevel());
                resultMap.put("code", "success");
                resultMap.put("data", clyjTouchVo);
                return resultMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("errorMsg", e.getMessage());
            return resultMap;
        } finally {
            registLock.unlock();
        }
        return null;
    }

    public List<ClyjFuyouSmallcompanyRegistervo> getTouch(String userid, Integer level) {
        try {
            ClyjFuyouSmallcompanyRegistervo clyjFuyouSmallcompanyRegistervo = new ClyjFuyouSmallcompanyRegistervo();
            Map map = new HashMap();
            //查询所有上级
            map.put("userid", userid);
            map.put("level", level);
            List<ClyjFuyouSmallcompanyRegistervo> clyjUserTouchList = clyjUserTouchMapper.selectall(map);
            for (int i = 0; i < clyjUserTouchList.size(); i++) {
                for (int j = 1; j < clyjUserTouchList.size(); j++) {
                    if (clyjUserTouchList.get(i).getUserPLevel() == clyjUserTouchList.get(j).getUserPLevel()) {
                        if (clyjUserTouchList.get(i).getRelationLevel() < clyjUserTouchList.get(j).getRelationLevel()) {
                            clyjUserTouchList.remove(j);
                        }
                        if (clyjUserTouchList.get(i).getRelationLevel() > clyjUserTouchList.get(j).getRelationLevel()) {
                            clyjUserTouchList.remove(i);
                        }
                    }
                }
            }
     /*   //查询店铺id
        QueryWrapper<ClyjNearbyShops> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("mich_id", userid);
        ClyjNearbyShops clyjNearbyShops = clyjNearbyShopsMapper.selectOne(queryWrapper1);
        //查询用户店铺开通富有账户id
        QueryWrapper<ClyjFuyouSmallcompanyRegister> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shops_id", clyjNearbyShops.getShopsId());
        ClyjFuyouSmallcompanyRegister clyjFuyouSmallcompanyRegister = clyjFuyouSmallcompanyRegisterMapper.selectOne(queryWrapper);
        clyjFuyouSmallcompanyRegistervo.setClyjFuyouSmallcompanyRegister(clyjFuyouSmallcompanyRegister);
        clyjUserTouchList.add(clyjFuyouSmallcompanyRegistervo);*/
            return clyjUserTouchList;
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();

        }
        return null;
    }

    /**
     * 订单过滤
     *
     * @param clyjGoodsOrderDetailsVo
     * @return
     */
    @Override
    @Transactional
    public ApiResult testOrders(ClyjGoodsOrderDetailsVo clyjGoodsOrderDetailsVo, ClyjUser clyjUser) {
        registLock.lock();
        try {
            // 获取订单信息
            List<ClyjGoodsOrderDetails> clyjGoodsOrderDetails = clyjGoodsOrderDetailsVo.getClyjGoodsOrderDetails();
            for (ClyjGoodsOrderDetails clyjGoodsOrderDetails1 : clyjGoodsOrderDetails) {
                // 下单商品数量
                BigDecimal i = new BigDecimal(clyjGoodsOrderDetails1.getGoodsAmount());
                // 支付积分
                BigDecimal c1 = clyjGoodsOrderDetails1.getPayIntegral();
                // 支付现金
                BigDecimal f1 = clyjGoodsOrderDetails1.getPayAmount();
                // 支付红包
                BigDecimal d1 = clyjGoodsOrderDetails1.getPayRedPacket();
                // 商品零钱
                BigDecimal b1 = clyjGoodsOrderDetails1.getPayBalance();
                // 校验订单类型
                Integer oedertype = clyjGoodsOrderDetails1.getOrderType();
                // 1.校验商品是否存在(订单类型 (1 首页订单 2 附近订单 3 积分兑换 4 红包兑换 5 零钱兑换 6 分润订单 7 礼品券订单 8 供应链订单 9 礼包订单))
                switch (oedertype) {
                    // 积分兑换
                    case OrderConstants.ORDER_TYPE_3:
                        // 1.判断积分商城商品是否存在
                        QueryWrapper<ClyjExchangeMall> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                        ClyjExchangeMall clyjExchangeMall = this.clyjExchangeMallMapper.selectOne(queryWrapper1);
                        if (clyjExchangeMall == null) return ApiResult.fail("积分商城商品不存在");
                        // 2.判断商品规格是否存在
                        QueryWrapper<ClyjGoodsSpec> queryWrapper2 = new QueryWrapper<>();
                        queryWrapper2.eq("spec_id", clyjGoodsOrderDetails1.getSpecId());
                        ClyjGoodsSpec clyjGoodsSpec = this.clyjGoodsSpecMapper.selectOne(queryWrapper2);

                        // 3.判断库存
                        if (clyjGoodsSpec == null && clyjGoodsSpec.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount())
                            return ApiResult.fail("积分商城库存不足", clyjGoodsSpec.getSpecNum());

                        // 现金和积分下单
                        boolean result = (c1 != null && c1.compareTo(BigDecimal.ZERO) > 0) && (f1 != null && f1.compareTo(BigDecimal.ZERO) > 0);
                        if (result == true) {
                            if ((c1.compareTo((new BigDecimal(clyjExchangeMall.getIntegral())).multiply(i)) < 0) ||
                                    (f1.compareTo((clyjExchangeMall.getPrice()).multiply(i)) < 0)) {
                                return ApiResult.fail("积分商城订单金额错误");
                            }
                        }

                        // 现金下单
                        boolean res = (c1 != null && c1.compareTo(BigDecimal.ZERO) > 0) && (f1 == null || f1.compareTo(BigDecimal.ZERO) == 0);
                        if (res == true) {
                            if (f1.compareTo(clyjExchangeMall.getPrice().multiply(i)) < 0) {
                                return ApiResult.fail("积分商城订单金额错误");
                            }
                        }
                        return ApiResult.success("积分商城订单认证成功");
                    // 红包兑换
                    case OrderConstants.ORDER_TYPE_4:
                        // 1.判断积分商城商品是否存在
                        QueryWrapper<ClyjExchangeMall> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                        ClyjExchangeMall clyjExchangeMal = this.clyjExchangeMallMapper.selectOne(queryWrapper);
                        if (clyjExchangeMal == null) return ApiResult.fail("红包兑换商品不存在");

                        // 2.判断商品规格是否存在
                        QueryWrapper<ClyjGoodsSpec> queryWrapper3 = new QueryWrapper<>();
                        queryWrapper3.eq("spec_id", clyjGoodsOrderDetails1.getSpecId());
                        ClyjGoodsSpec goodsSpec = this.clyjGoodsSpecMapper.selectOne(queryWrapper3);

                        // 3.判断库存
                        if (goodsSpec == null || goodsSpec.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount())
                            return ApiResult.fail("红包兑换库存不足", goodsSpec.getSpecNum());

                        boolean re = d1 != null && d1.compareTo(BigDecimal.ZERO) > 0;
                        if (re == true) {
                            if (d1.compareTo(clyjExchangeMal.getRedPacket().multiply(i)) < 0) {
                                return ApiResult.fail("红包兑换订单金额错误");
                            }
                        }
                        return ApiResult.success("红包兑换认证成功");
                    // 礼品券兑换金额订单
                    case OrderConstants.ORDER_TYPE_7:
                        // 校验订单是否存在
                        QueryWrapper<ClyjScmGoodsZdy> queryWrapper4 = new QueryWrapper<>();
                        queryWrapper4.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                        ClyjScmGoodsZdy clyjScmGoodsZdy = this.clyjScmGoodsZdyMapper.selectOne(queryWrapper4);
                        if (clyjScmGoodsZdy == null) return ApiResult.fail("礼品券兑换商品不存在");

                        // 2.校验商品库存
                        QueryWrapper<ClyjScmGoodsSpecZdy> queryWrapper5 = new QueryWrapper<>();
                        queryWrapper5.eq("spec_id", clyjGoodsOrderDetails1.getSpecId());
                        ClyjScmGoodsSpecZdy clyjScmGoodsSpecZdy = clyjScmGoodsSpecZdyMapper.selectOne(queryWrapper5);
                        if (clyjScmGoodsSpecZdy == null || clyjScmGoodsSpecZdy.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount())
                            return ApiResult.fail("礼品券兑换库存不足", clyjScmGoodsSpecZdy.getSpecNum());

                        // 支付礼品券
                        BigDecimal e1 = clyjGoodsOrderDetails1.getPayCoupon();
                        // 礼品券
                        boolean resul = e1 != null && e1.compareTo(BigDecimal.ZERO) > 0;
                        if (resul == true) {
                            if (e1.compareTo(clyjScmGoodsSpecZdy.getSpecPriceNew().multiply(i)) < 0) {
                                return ApiResult.fail("礼品券兑换订单金额错误");
                            }
                        }
                        return ApiResult.success("红包兑换认证成功");
                    // 首页商品下单
                    case OrderConstants.ORDER_TYPE_1:
                        // 校验商品是否存在
                        QueryWrapper<ClyjGoodsHomepage> queryWrapper6 = new QueryWrapper<>();
                        queryWrapper6.eq("goods_id", clyjGoodsOrderDetails1.getGoodsId());
                        ClyjGoodsHomepage clyjGoodsHomepage = clyjGoodsHomepageMapper.selectOne(queryWrapper6);
                        if (clyjGoodsHomepage == null) return ApiResult.fail("首页商品不存在");

                        // 校验商品库存是否充足
                        QueryWrapper<ClyjGoodsSpec> queryWrapper7 = new QueryWrapper<>();
                        queryWrapper7.eq("spec_id", clyjGoodsOrderDetails1.getSpecId());
                        ClyjGoodsSpec goodsSpec1 = this.clyjGoodsSpecMapper.selectOne(queryWrapper7);
                        // 判断库存
                        if (goodsSpec1 == null || goodsSpec1.getSpecNum() < clyjGoodsOrderDetails1.getGoodsAmount())
                            return ApiResult.fail("首页商品库存不足", goodsSpec1.getSpecNum());

                        boolean rest = (f1 != null || f1.compareTo(BigDecimal.ZERO) > 0);
                        if (rest == true) {
                            if (f1.compareTo(goodsSpec1.getSpecPriceNew().multiply(i)) < 0) {
                                return ApiResult.fail("首页商品订单金额错误");
                            }
                        }
                        if (b1 != null || b1.compareTo(BigDecimal.ZERO) > 0) {
                            if (b1.compareTo(clyjGoodsHomepage.getPocketMoney()) != 0) {
                                return ApiResult.fail("首页商品订单零钱金额错误");
                            }
                        }
                        break;
                    // 附近商品订单
                    case OrderConstants.ORDER_TYPE_2:
                        BigDecimal amounts = BigDecimal.ZERO;
                        BigDecimal balances = BigDecimal.ZERO;
                        // 获取购买的商品
                        List<ClyjGoodsOrderDetails> details = clyjGoodsOrderDetailsVo.getDetails();
                        for (ClyjGoodsOrderDetails detail : details) {
                            // 判断商品是否存在
                            QueryWrapper<ClyjNearbyShopsGoods> queryWrapper8 = new QueryWrapper<>();
                            queryWrapper8.eq("goods_id", detail.getGoodsId());
                            ClyjNearbyShopsGoods clyjNearbyShopsGoods = clyjNearbyShopsGoodsMapper.selectOne(queryWrapper8);
                            if (clyjNearbyShopsGoods == null) return ApiResult.fail("附近商品商品不存在");

                            // 附近支付商品零钱
                            BigDecimal balance = detail.getPayBalance();
                            // 附近实际支付金额
                            BigDecimal amount = detail.getPayAmount();
                            // 商品数量
                            Integer goodsAmount = detail.getGoodsAmount();
                            // 判断商品库存充足
                            QueryWrapper<ClyjNearbyShopsGoodsSpec> wrapper = new QueryWrapper<>();
                            wrapper.eq("spec_id", detail.getSpecId());
                            ClyjNearbyShopsGoodsSpec clyjNearbyShopsGoodsSpec = clyjNearbyShopsGoodsSpecMapper.selectOne(wrapper);
                            // 如果有商品规格
                            if (clyjNearbyShopsGoodsSpec == null) {
                                // 如果规格不存在直接判断商品库存
                                if (clyjNearbyShopsGoods.getStock() < detail.getGoodsAmount()) {
                                    return ApiResult.fail("附近商品库存不足", clyjNearbyShopsGoods.getStock());
                                }

                                // 判断商品的零钱是否正确
                                boolean ret = clyjNearbyShopsGoodsSpec.getSpecSmallChange() == null ||
                                        clyjNearbyShopsGoodsSpec.getSpecSmallChange().equals(BigDecimal.ZERO) ||
                                        !balance.equals(clyjNearbyShopsGoodsSpec.getSpecSmallChange().multiply(new BigDecimal(goodsAmount)));

                                if (ret == true) {
                                    return ApiResult.fail("附近商品零钱错误", null);
                                }

                                // 判断支付金额是否正确
                                boolean ult = clyjNearbyShopsGoodsSpec.getSpecPresentPrice() != null ||
                                        BigDecimal.ZERO.equals(clyjNearbyShopsGoodsSpec.getSpecPresentPrice()) ||
                                        !amount.equals(new BigDecimal(goodsAmount).multiply(clyjNearbyShopsGoodsSpec.getSpecPresentPrice()));

                                if (ult == true) {
                                    return ApiResult.fail("附近商品商品金额错误", null);
                                }
                            } else {
                                // 无规格商品价格校验
                                boolean reu = clyjNearbyShopsGoods.getPresentPrice() == null ||
                                        BigDecimal.ZERO.equals(clyjNearbyShopsGoods.getPresentPrice()) ||
                                        !amount.equals(new BigDecimal(goodsAmount).multiply(clyjNearbyShopsGoods.getPresentPrice()));
                                if (reu == true) {
                                    return ApiResult.fail("附近商品商品金额错误", null);
                                }
                                // 无规格商品零钱校验
                                boolean ul = clyjNearbyShopsGoods.getSmallChange() == null ||
                                        BigDecimal.ZERO.equals(clyjNearbyShopsGoods.getSmallChange()) ||
                                        !amount.equals(clyjNearbyShopsGoods.getSmallChange().multiply(new BigDecimal(goodsAmount)));
                                if (ul == true) {
                                    return ApiResult.fail("附近商品商品零钱金额错误", null);
                                }
                            }
                            // 订单支付总额
                            amounts = amounts.add(amount);
                            // 零钱支付总额
                            balances = balances.add(balance);
                        }
                        if (!f1.equals(amounts) || !b1.equals(balances)) {
                            return ApiResult.fail("附近商品商品订单金额或零钱错误", null);
                        }
                        break;
                    default:
                        throw new Exception("currency 不支持");
                }
                List<ClyjFuyouSmallcompanyRegistervo> clyjTouchVo = getTouch(clyjUser.getUserId(), clyjUser.getLevel());
                logger.debug("查询分润成功");
                return ApiResult.success(clyjTouchVo);
            }
        } catch (Exception e) {
            logger.debug("---->>>>>---->>>>>订单校验失败", e.getMessage());
        } finally {
            registLock.unlock();
        }
        return ApiResult.fail("订单校验失败，请重新下单！");
    }
}